/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.view.common.html;

import java.util.HashMap;
import java.util.Map;

/**
 * Provides methods to XML encode strings.
 * 
 * @author Scott Rossillo
 *
 */
public class HTMLEncoder {
	
	private final static Map charMap = new HashMap();
	
	static {
		// initialize the character map
		charMap.put(">", "&gt;");
		charMap.put("<", "&lt;");
		charMap.put("&", "&amp;");
		charMap.put("\"", "&quot;");
		charMap.put("'", "&#039;");
		charMap.put("\\", "&#092");
	}
	
	private static String encodeSingleCharacter(String ch) {
		
		String enc = (String)charMap.get(ch);
		
		return enc != null ? enc : ch;
	}
	
	/**
	 * Returns an XML encoded version of the given string.
	 * 
	 * @param xml the string to encode
	 * @return an XML encoded version of the given <code>xml</code>
	 */
	public static String encodeXML(String xml) {
		
		if(xml == null) {
			return null;
		}
		
		StringBuffer buf = new StringBuffer(xml.length() * 2);
		char ch;
		for(int i = 0; i < xml.length(); i++) {
			ch = xml.charAt(i);
			if(Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
				buf.append(ch);
			} else {
				buf.append(encodeSingleCharacter(String.valueOf(ch)));
			}
		}
		
		return buf.toString();
	}
	
	private HTMLEncoder() { }

}
